package com.cxyzy.demo

import android.os.Bundle
import android.view.View.GONE
import android.view.View.VISIBLE
import androidx.appcompat.app.AppCompatActivity
import com.afollestad.assent.Permission
import com.afollestad.assent.runWithPermissions
import com.baidu.location.BDAbstractLocationListener
import com.baidu.location.BDLocation
import com.baidu.location.LocationClient
import com.baidu.location.LocationClientOption
import com.cxyzy.demo.Utils.getLocationStr
import kotlinx.android.synthetic.main.activity_main.*


class MainActivity : AppCompatActivity() {
    private lateinit var mLocationClient: LocationClient
    private val myListener = MyLocationListener()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        initMap()
        locateBtn.setOnClickListener { locate() }
    }

    private fun initMap() {
        mLocationClient = LocationClient(applicationContext)
        //声明LocationClient类
        mLocationClient.registerLocationListener(myListener)
        val option = LocationClientOption()

        //可选，是否需要地址信息，默认为不需要，即参数为false
        //如果开发者需要获得当前点的地址信息，此处必须为true
        option.setIsNeedAddress(true)

        //mLocationClient为第二步初始化过的LocationClient对象
        //需将配置好的LocationClientOption对象，通过setLocOption方法传递给LocationClient对象使用
        //更多LocationClientOption的配置，请参照类参考中LocationClientOption类的详细说明
        mLocationClient.locOption = option

    }

    private fun locate() {
        locationTv.text = ""
        runWithPermissions(Permission.ACCESS_FINE_LOCATION) {
            progressBar.visibility = VISIBLE
            mLocationClient.start()
        }

    }

    inner class MyLocationListener : BDAbstractLocationListener() {
        override fun onReceiveLocation(location: BDLocation) {
            progressBar.visibility = GONE
            locationTv.text = getLocationStr(location)
        }
    }
}
